package org.edu.modules.jxrw.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.edu.modules.jxrw.entity.PkmxResult;
import org.edu.modules.jxrw.service.IExcelService;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import java.awt.*;
import java.io.BufferedOutputStream;
import java.util.List;

/**
 * @author xlz
 */
@Service
public class ExcelServiceImpl implements IExcelService {

    /** 表头 */
    private String[] weeks = {"节次/星期","星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"};
    /** 节次 */
    private String[] sections = {
            "第一节\r\n08:00-08:45",
            "第二节\r\n09:00-09:45",
            "第三节\r\n10:00-10:45",
            "第四节\r\n11:00-11:45",
            "第五节\r\n14:00-14:45",
            "第六节\r\n15:00-15:45",
            "第七节\r\n16:00-16:45",
            "第八节\r\n17:00-17:45",
            "第九节\r\n19:00-19:45",
            "第十节\r\n20:00-20:45",
    };
    /** 间隔 */
    private String[] intervals = {"午休", "晚自习"};

    @Override
    public void export(String title, List<PkmxResult> data, ServletOutputStream out) {
        // 创建excel文件对应的对象
        HSSFWorkbook work = new HSSFWorkbook();
        // 添加标签
        HSSFSheet sheet = work.createSheet(title);
        // 生成表格
        this.addBorder(work, sheet);
        // 生成模板
        this.createTemplate(work, sheet);
        // 填充数据
        this.fillData(work, sheet, data);

        // 返回excel表格
        try {
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(out);
            bufferedOutputStream.flush();
            work.write(bufferedOutputStream);
            bufferedOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void exportKbs(JSONObject data, ServletOutputStream out) {
        // 创建excel文件对应的对象
        HSSFWorkbook work = new HSSFWorkbook();

        JSONArray list = data.getJSONArray("data");
        for(int i = 0; i < list.size(); i++){
            // 添加标签
            HSSFSheet sheet = work.createSheet(list.getJSONObject(i).getString("xzbmc"));
            // 生成表格
            this.addBorder(work, sheet);
            // 生成模板
            this.createTemplate(work, sheet);
            List<PkmxResult> pxList = list.getJSONObject(i).getJSONArray("kbs").toJavaList(PkmxResult.class);
            // 填充数据
            this.fillData(work, sheet, pxList);
        }
        // 返回excel表格
        try {
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(out);
            bufferedOutputStream.flush();
            work.write(bufferedOutputStream);
            bufferedOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 创建表格（添加边框）
     */
    private void addBorder(HSSFWorkbook work, HSSFSheet sheet){
        HSSFCellStyle style= work.createCellStyle();
        //边框
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 居中
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        style.setLocked(false);
        style.setWrapText(true);

        HSSFRow row = null;
        for (int i = 0; i < 13; i ++){
            row = sheet.createRow(i);
            row.createCell(0).setCellStyle(style);
            row.createCell(1).setCellStyle(style);
            row.createCell(2).setCellStyle(style);
            row.createCell(3).setCellStyle(style);
            row.createCell(4).setCellStyle(style);
            row.createCell(5).setCellStyle(style);
            row.createCell(6).setCellStyle(style);
            row.createCell(7).setCellStyle(style);
        }
    }

    /**
     * 创建课表的模板
     */
    private void createTemplate(HSSFWorkbook work, HSSFSheet sheet){
        // 设置表头颜色
        HSSFPalette palette = work.getCustomPalette();
        palette.setColorAtIndex(HSSFColor.LAVENDER.index, (byte)102, (byte)195, (byte)253);
        HSSFColor headerColor = palette.getColor(HSSFColor.LAVENDER.index);

        // 设置字体大小
        HSSFFont font_white_11 = work.createFont();
        font_white_11.setColor(HSSFColor.WHITE.index);
        font_white_11.setFontHeightInPoints((short)11);

        // 在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
        HSSFRow row = sheet.getRow(0);
        // 设置行高
        row.setHeightInPoints(30);
        // 创建单元格容器
        HSSFCell cell = null;
        // 表头
        for(int i = 0; i < weeks.length; i++){
            cell = row.getCell(i);
            HSSFRichTextString text = new HSSFRichTextString(weeks[i]);
            text.applyFont(font_white_11);
            cell.setCellValue(text);
            sheet.setColumnWidth(cell.getColumnIndex(), 256 * 30);

            HSSFCellStyle style = work.createCellStyle();
            style.cloneStyleFrom(cell.getCellStyle());
            // 设置背景色
            style.setFillForegroundColor(headerColor.getIndex());
            cell.setCellStyle(style);
        }
        // 设置间隔
        for(int i = 0; i < intervals.length; i++){
            int rowIndex = (i + 1) * 5;
            row = sheet.getRow(rowIndex);
            // 设置行高
            row.setHeightInPoints(30);
            cell = row.getCell(0);
            HSSFRichTextString text = new HSSFRichTextString(intervals[i]);
            text.applyFont(font_white_11);
            cell.setCellValue(text);
            // 合并单元格
            sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex,0, 7));

            HSSFCellStyle style = work.createCellStyle();
            style.cloneStyleFrom(cell.getCellStyle());
            // 设置背景色
            style.setFillForegroundColor(headerColor.getIndex());
            cell.setCellStyle(style);
        }
        // 设置节次信息
        for(int i = 0; i < sections.length; i++){
            int rowIndex;
            if(i < 4){
                rowIndex = i + 1;
            } else if(i < 8){
                rowIndex = i + 2;
            } else{
                rowIndex = i + 3;
            }
            row = sheet.getRow(rowIndex);
            cell = row.getCell(0);
            cell.setCellValue(new HSSFRichTextString(sections[i]));
            sheet.setColumnWidth(cell.getColumnIndex(), 256 * 15);

            HSSFCellStyle style = work.createCellStyle();
            style.cloneStyleFrom(cell.getCellStyle());
            // 设置背景色
            style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            cell.setCellStyle(style);
        }

    }

    /**
     * 填充数据
     */
    private void fillData(HSSFWorkbook work, HSSFSheet sheet, List<PkmxResult> data){
        HSSFRow row = null;
        HSSFCell cell = null;
        for(PkmxResult item : data){
            int rowIndex = item.getSection();
            int cellIndex = item.getWeek();

            if(rowIndex <= 4){
            } else if(rowIndex <= 8){
                rowIndex += 1;
            } else if(rowIndex <= 12){
                rowIndex += 2;
            }

            row = sheet.getRow(rowIndex);
            cell = row.getCell(cellIndex);
            cell.setCellValue(item.getKcmc() + "\r\n" + item.getJsmc() + "\r\n" + item.getJsxm());
        }
    }
}
